package lx6;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class MyThread extends Thread {
    public Socket socket;

    public MyThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {

            //读取客服端发来的文件数据，并保持到本地文件当中
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            String name = UUID.randomUUID().toString().replace("-", "");
            //创建一个输出流
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("..\\day56\\Server\\" + name + ".jpg"));
            //边读边写
            byte[] bytes = new byte[1024];
            int len;
            while (((len = bis.read(bytes)) != -1)) {
                bos.write(bytes, 0, len);
            }
            bos.close();
            //到了这里说明文件已经写完了
            //向客服端发送反馈说明上传成功了
            //一句话我们可以使用字符缓冲流
            String str = "上传成功";
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write(str);


        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭流
            try {
              if (socket != null) {
                  socket.close();//断开了与客服端的连接
              }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
